import sys
import json

from PySide6.QtWidgets import QWidget, QGridLayout, QLabel, QTextEdit, QPushButton, QHBoxLayout, QVBoxLayout, QApplication, QFileDialog, QLineEdit
from easy_tools.ui.utils.code_text_editor_widget import CodeTextEdit
from easy_tools.ui.utils import *


class JsonMappingCompareWidget(QWidget):

    def __init__(self):
        super().__init__()
        self._init()

    def _init(self):
        grid = QGridLayout(self)
        self.file_path = ''
        self.dict = {}
        self.setLayout(grid)
        self.input_widget = CodeTextEdit('', self)
        self.json_check_widget = QLabel('不是有效的JSON', self)
        self.json_check_widget.setStyleSheet("color: red")
        self.json_check_widget.hide()

        self.encoding = QLineEdit('utf-8', self)
        self.sep = QLineEdit(':', self)
        self.dict_label_widget = QLabel('(一行一条映射)', self)
        self.dict_widget = QPushButton('选择字典文件', self)
        self.output_widget = QTextEdit('', self)
        self.confirm = QPushButton('转换', self)

        box = QVBoxLayout(self)
        box.addLayout(new_hbox(QLabel("文件编码: ", self), self.encoding))
        box.addLayout(new_hbox(QLabel('分隔符: ', self), self.sep))
        box.addLayout(new_hbox(self.dict_label_widget, self.dict_widget))
        box.addWidget(self.confirm)

        x = 0
        grid.addWidget(QLabel('JSON: ', self), x, 0)
        grid.addWidget(self.input_widget, x, 1)
        grid.addLayout(box, x, 2)
        grid.addWidget(QLabel("映射JSON: ", self), x, 3)
        grid.addWidget(self.output_widget, x, 4)

        x += 1
        grid.addWidget(self.json_check_widget, x, 1)

        self.input_widget.textChanged.connect(self._json_check)
        self.dict_widget.clicked.connect(self._choice_dict_file)
        self.confirm.clicked.connect(self._mapping)

    def _choice_dict_file(self):
        file_name, _ = QFileDialog.getOpenFileName(self)
        if file_name:
            with open(file_name, 'r', encoding='utf-8') as f:
                 for line in f.readlines():
                    v = line.strip('\n').split(self.sep.text())
                    if len(v) == 2:
                        self.dict[v[0]] = v[1]
            self.dict_label_widget.setText(f'导入字典数: {len(self.dict)}条')
            self.dict_widget.setText('重新选择')

    def _json_check(self):
        text = self.input_widget.toPlainText()
        try:
            json.loads(text)
            self.json_check_widget.hide()
        except json.decoder.JSONDecodeError:
            self.json_check_widget.show()

    def _mapping(self):
        try:
            text = self.input_widget.toPlainText()
            v = json.loads(text)
            self._dfs_json_mapping(v)
            self.output_widget.setText(json.dumps(v, indent=4, ensure_ascii=False))
        except json.decoder.JSONDecodeError:
            pass

    def _dfs_json_mapping(self, v):
        if isinstance(v, list):
            for one in v:
                self._dfs_json_mapping(one)
        elif isinstance(v, dict):
            keys = list(v.keys())
            for key in keys:
                self._dfs_json_mapping(v[key])
                if self.dict.get(key):
                    v[self.dict[key]] = v[key]
                    del v[key]


if __name__ == '__main__':
    app = QApplication()
    win = JsonMappingCompareWidget()
    win.show()
    sys.exit(app.exec())
